<?php
ini_set('display_errors', '1');
session_start();
include 'func.php';


$con = connectToDB();

$userId = getSessionUserID();
$testId =  $con->real_escape_string( $_POST['test_id']);

if ($userId == null)
{
    // to do: handle new users who haven't registered
}

$stmt = $con->prepare("INSERT INTO testattempts(userid, testid) VALUES(?, ?)");
$stmt->bind_param('ii', $userId, $testId);
$stmt->execute(); 
$stmt->close();

$testAttemptID = $con->insert_id;

// ENGLISH
$totalCorrect = 0;
for($i = 1; $i < 76; $i++)
{
    $selectedAnswer = $_POST["answer_1_".$i];
    $answerInfo  = getCorrectAnswerFor($testId, 1, $i);
    
    $correctAnswer = $answerInfo[0];
    $questionId = $answerInfo[1];
    

    if (strcasecmp($selectedAnswer, $correctAnswer) == 0)
    {
        $isCorrect = true;
        $totalCorrect++;
    }
    else
    {
        $isCorrect = false;
        echo $i.".) Selected--> ".$selectedAnswer."\t correct-->".$correctAnswer;
    }
    
    insertQuestionAttempt($testAttemptID, $questionId, $selectedAnswer, $isCorrect);
    
}

// MATH
for($i = 1; $i < 61; $i++)
{
    $selectedAnswer = $_POST["answer_2_".$i];
    $answerInfo  = getCorrectAnswerFor($testId, 2, $i);
    
    $correctAnswer = $answerInfo[0];
    $questionId = $answerInfo[1];
    

    if (strcasecmp($selectedAnswer, $correctAnswer) == 0)
    {
        $isCorrect = true;
        $totalCorrect++;
    }
    else
    {
        $isCorrect = false;
        echo $i.".) Selected--> ".$selectedAnswer."\t correct-->".$correctAnswer;
    }
    
    insertQuestionAttempt($testAttemptID, $questionId, $selectedAnswer, $isCorrect);
}

// READING
for($i = 1; $i < 41; $i++)
{
    $selectedAnswer = $_POST["answer_3_".$i];
    $answerInfo  = getCorrectAnswerFor($testId, 3, $i);
    
    $correctAnswer = $answerInfo[0];
    $questionId = $answerInfo[1];
    

    if (strcasecmp($selectedAnswer, $correctAnswer) == 0)
    {
        $isCorrect = true;
        $totalCorrect++;
    }
    else
    {
        $isCorrect = false;
        echo $i.".) Selected--> ".$selectedAnswer."\t correct-->".$correctAnswer;
    }
    
    insertQuestionAttempt($testAttemptID, $questionId, $selectedAnswer, $isCorrect);
}

for($i = 1; $i < 41; $i++)
{
    $selectedAnswer = $_POST["answer_4_".$i];
    $answerInfo  = getCorrectAnswerFor($testId, 4, $i);
    
    $correctAnswer = $answerInfo[0];
    $questionId = $answerInfo[1];
    

    if (strcasecmp($selectedAnswer, $correctAnswer) == 0)
    {
        $isCorrect = true;
        $totalCorrect++;
    }
    else
    {
        $isCorrect = false;
        echo $i.".) Selected--> ".$selectedAnswer."\t correct-->".$correctAnswer;
    }
    
    insertQuestionAttempt($testAttemptID, $questionId, $selectedAnswer, $isCorrect);
}

header('Location: test_result.php?t_id='.$testAttemptID);